<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 对账单
 *
 * @icon fa fa-circle-o
 */
class Duizhang extends Backend
{

    protected $dataLimit = true;
    protected $dataLimitField = 'chengyun_id';
    protected $noNeedRight = ['*'];
    /**
     * Duizhang模型对象
     * @var \app\admin\model\Duizhang
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Duizhang;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $key=>$value)
            {
                $value['fayun_id']=get_fayun($value['fayun_id']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 提交客户确认
     * @param null $ids
     * @throws \think\exception\DbException
     */
    public function tijiao($ids=null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row->where("id",$ids)->update(['tijiaotime'=>time()]);
        $this->success("提交客户成功,请等待客户确认及打款");
    }


    /**
     * 取得发运人
     */
    public function getfayun()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        $m_fayun = new \app\admin\model\Fayunren();
        $total = $m_fayun->where("id", ">", 1)->count();
        $list = $m_fayun->where("id", ">", 1)
            ->page($page, $pagesize)
            ->select();

        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);

    }

    public function xuanzhe($ids=null)
    {
        if ($this->request->isPost()) {
            $this->success("模拟启动成功".$ids.json_encode(input("param.")));
        }
        $this->assign("jiesuandanid",$ids);
        $this->assignconfig("duizhangid",$ids);
        return $this->view->fetch();

    }


    public function addyundan($ids=null)
    {
        if ($this->request->isPost()) {

            $jiesuanid = input("params/d", 0);
            if (!$jiesuanid) $this->error("结算单ID不能为空");
            $m_duizhang = new \app\admin\model\Duizhang();
            $duizhanginfo = $m_duizhang->where("id", $jiesuanid)->find();
            if (!$duizhanginfo) $this->error("结算单未找到!");
           // dump(collection($duizhanginfo)->toArray());
            if ($duizhanginfo['querentime'] > 86400) $this->error("用户已确认不可修改");

            $m_yundan=new \app\admin\model\Yundan();

            $m_yundan->where('id', 'in', $ids)->update(['duizhang_id' => $jiesuanid] );

            $money=$m_yundan->where("id","in",$ids)->sum("yunfei");
            $duizhanginfo->save(['jine'=>$duizhanginfo['jine']+$money],["id"=>$jiesuanid]);
         //   echo $duizhanginfo->getLastSql();




            $this->success("模拟启动成功" );
        }

    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //  //不可删除
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $bainhao=date("ymdHis").rand(10,99);
        $this->assign("bianhao",$bainhao);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if($v['querentime']>0)  continue;
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }





    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['querentime']>0)  $this->error(__('客户已确认,不能修改'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            //不可删除
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
